<template>
  <div id="personalCenter">

    <div class="background">
      <img alt="logo" src="@/assets/user/background.png" style="width: 100%;height: 99%">
    </div>

    <span><img alt="cheer" src="@/assets/user/2.png" style="width: 3%;height:4%;margin-left: 2%;position: absolute;top: 11px;" ></span>
    <span style="margin-left: 5%;position: absolute;top: 15px">&nbsp;&nbsp;欢迎使用team-Team!</span>

    <div id="title" style="text-align: center;margin-top: 3%;font-size: 350%">个人中心</div>
    <br/>
    <div id="subTitle" style="text-align: center;font-size: 100%">管理你的账户</div>

    <div>
      <el-button style="background-color: #A4ADB3;
            width: 110px;height: 50px;color: white;
            border-radius: 6px;
            border: none;margin-left: 100px;margin-right: 170px;"
              @click="backToHome">返回工作台</el-button>


      <div class="wrap" style="text-align: center;margin-top: 4%;margin-left: 5%;height: 500px" >
        <el-container>
          <el-aside width="25%" >
            <div><img
              style="width:100px;height:100px;border-radius: 50%;margin-top: 30%;margin-left: -5%"
              :src="tableData.userPicture"
            ></div>
            <el-link :underline="false" @click="changePhoto()">Edit</el-link>
          </el-aside>


          <el-main style="text-align: left;margin-left: 20px;margin-top: 10px">
            <div style="margin-top: 1%">TrueName</div>
            <div style="font-size: 80%;color: gray">{{ tableData.userRealName }}</div>
            <div style="margin-top: 0.5%">Email</div>
            <div style="font-size: 80%;color: gray">{{ tableData.userEmail }}</div>
            <div style="margin-top: 1%">NickName</div>
            <div style="font-size: 80%;color: gray">{{ tableData.userNickName }}</div>
            <el-link :underline="false" style="color: cornflowerblue;font-size: 60%;margin-top: -5%" @click="changeName()">Change name</el-link>
            <div style="margin-top: 0.5%">Password</div>
            <el-link :underline="false" style="color: cornflowerblue;font-size: 60%;margin-top: -5%" @click="changePassword()">Change password</el-link>
            <div style="margin-top: 0.5%">Last Login</div>
            <div style="font-size: 80%;color: gray">{{ tableData.lastLogin }}</div>

          </el-main>
        </el-container>

        <el-dialog
          title="修改密码"
          :visible.sync="editDialogVisible"
          width="50%"
          :before-close="handleClose"
          :append-to-body="true"
        >
          <!-- 表单区域 -->
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="ruleForm.userName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="旧密码" prop="userPasswordOld">
              <el-input type="password" v-model="ruleForm.userPasswordOld" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="userPasswordNew">
              <el-input type="password" v-model="ruleForm.userPasswordNew" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
              <el-input type="password" v-model="ruleForm.checkPassword" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item class="submit-button">
              <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
    </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "PersonalCenter",
  data(){
    var checkUsername = (rule, value, callback) => {
      const reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
      if (!value  || value === '') {
        callback(new Error('用户名不能为空'));
      } else{
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入旧密码'));
      }else {
        callback();
      }
    };
    var validatePass1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPassword !== '') {
          this.$refs.ruleForm.validateField('checkPassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.userPasswordNew) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return{
      ruleForm: {
        userName: '',
        userPasswordOld:'',
        userPasswordNew: '',
        checkPassword:'',
      },
      rules: {
        userName: [
          {validator: checkUsername, trigger: 'blur'}
        ],
        userPasswordOld: [
          { validator: validatePass, trigger: 'blur' }
        ],
        userPasswordNew: [
          { validator: validatePass1, trigger: 'blur' }
        ],
        checkPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      editDialogVisible:false,
      uploadImgUrl: 'http://43.138.82.70/api/rs/image/upload',
      imgList: [],
      picture:'',
      tableData: {
        userID:'',
        userNickName: '',
        userRealName: '',
        userPassword: '',
        userEmail:'',
        userPhoneNumber:'',
        userPicture:'',
        lastLogin:'',
      },
    }
  },
  created () {
    this.getInfo();
  },
  methods:{
    submitForm(formName) {
      const self = this;
      const formData = new FormData();
      formData.append("userName", self.ruleForm.userName);
      formData.append("userPasswordOld", self.ruleForm.userPasswordOld);
      formData.append("userPasswordNew", self.ruleForm.userPasswordNew);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          self.$axios({
            method: 'post',
            url: '/user/psd',
            data: formData,
          })
            .then(res => {
              console.log(res);
              console.log(res.data.errno);
              if(res.data.errno===0) {
                this.$message.success('修改成功！');
                setTimeout(() => {
                  window.location.reload();
                }, 1500);
              }else{
                this.$message.error(res.data.msg);
              }
            })
            .catch(err => {
              console.log(err);
            })
        } else {
          console.log('提交失败!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClose(done) {
      this.editDialogVisible=false;
    },
    getInfo() {
      window.alert(this.$store.state.ID);
      const self = this;

      this.$axios({
        method: 'get',           /* 指明请求方式，可以是 get 或 post */
        url: '/user/info',       /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */
        params:{
          userID:this.$store.state.ID
        }
      })
        .then(res => {              /* res 是 response 的缩写 */

          this.tableData=res.data.data[0];
        })
        .catch(err => {
          /* 若出现异常则在终端输出相关信息 */
        })
    },
    changePhoto(){

    },
    backToHome(){
      this.$router.push('/team/member');
    },
    changeName(){
      this.$prompt('请输入新用户名', 'Change name', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        const self = this;
        const formData = new FormData();
        formData.append("newNickname", value);
        formData.append("userID", this.$store.state.ID);
        self.$axios({
          method: 'post',
          url: '/user/name',
          data: formData,
        })
          .then(res => {
            console.log(res);
            console.log(res.data.errno);
            if(res.data.errno===0) {
              this.$message({
                type: 'success',
                message: '你的新用户名是: ' + value
              });
              setTimeout(() => {
                window.location.reload();
              }, 600);
            }
            else{
              this.$message.error(res.data.msg);
            }
          })
          .catch(err => {
          console.log(err);
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },

    changeEmail(){
      this.$prompt('请输入邮箱', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: '邮箱格式不正确'
      }).then(({ value }) => {
        const self = this;
        const formData = new FormData();
        formData.append("newNickname", value);
        formData.append("userID", this.$store.state.ID);
        self.$axios({
          method: 'post',
          url: '/user/name',
          data: formData,
        })
          .then(res => {
            console.log(res);
            console.log(res.data.errno);
            if(res.data.errno===0) {
              this.$message({
                type: 'success',
                message: '你的新邮箱是: ' + value
              });
              setTimeout(() => {
                window.location.reload();
              }, 600);
            }
            else{
              this.$message.error(res.data.msg);
            }
          })
          .catch(err => {
            console.log(err);
          })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    changePassword(){
      window.alert("wrong");
      this.editDialogVisible=true;
    },
  }
}
</script>

<style scoped>

.background {
  width: 100%;
  height: 100%; /**宽高100%是为了图片铺满屏幕 */
  top: 0%;
  z-index: -1;
  position: absolute;

}
.wrap {
  width: 40%;
  height: 55vh;
  padding: 0 25px 0 25px;
  line-height: 40px;
  display: inline-block;
  background-color: rgb(255, 255, 255);
  border-radius: 20px;
}


</style>
